const onLogin = function () {
    const login_form = document.querySelector('.login_form')
    const usernameInput = document.querySelector('input[name="username"]')
    const passwordInput = document.querySelector('input[name="password"]')

    const username_p = document.querySelector('.username_p')
    const password_p = document.querySelector('.password_p')
    const login_p = document.querySelector('.login_p')

    login_form.addEventListener('submit', function (e) {
        // 阻止默认行为
        e = e || window.event
        e.preventDefault()


        const username = usernameInput.value
        var password = passwordInput.value
        
        // console.log('password:',password);
        

        
        // 表单非空验证
        if (username == '') {
            username_p.innerHTML = '请输入手机号!'
            return false
        } else {
            username_p.innerHTML = ''
        }

        if (password == '') {
            password_p.innerHTML = '请输入密码!'
            return false
        } else {
            password_p.innerHTML = ''
        }

        password = sha256(password)
        // console.log(password);
        // 登录请求
        myAxios({
            method: 'post',
            url: '/users/login',
            data: {
                username,
                password,
            },
        }).then(res => {
            let { code, info, token } = res.data
            if (code == 1) {
                // 保存用户信息
                const user = info
                localStorage.setItem('user', JSON.stringify(user))
                // 保存token用于服务端请求验证，保存1天
                Cookies.set('TOKEN', token, { expires: 1 })
                login_p.innerHTML = '登录成功！'
                location.href = './home.html'
            } else {
                login_p.innerHTML = '手机号或验证码错误！'
            }
        })
    })
}